package com.huadi.qi.controller;

import com.huadi.qi.bean.User;
import com.huadi.qi.mapper.UserMapper;
import com.huadi.qi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    @Autowired
    UserMapper userMapper;
    @Autowired
    UserService userService;

    //  登录页面
    @GetMapping(value = {"/", "/login"})
    public String login(){
        return "login";
    }
    // post 重定向
    @PostMapping("/login")
    public String post(String userId,String userPwd,HttpSession session, Model model){
        System.out.println(userId);
        System.out.println(userPwd);
        User user = userMapper.selectByUsername(String.valueOf(userId));
        try {
            if (user.getUsername().equals(userId) && user.getPassword().equals(userPwd)){
//            session.getAttribute("loginUser",user);
                session.setAttribute("loginUser",user);
                return "redirect:/index.html";
            }else {
                //登录失败，给出提示
                model.addAttribute("msg", "账号密码错误");
                //返回登录界面
                return "login";
            }
        }catch (Exception e){
            //登录失败，给出提示
            model.addAttribute("msg", "账号密码错误");
            //返回登录界面
            return "login";
    }
        }
//  主页
    @GetMapping("/index.html")
    public String index(){
        return "index";
    }
}
